/**
 * Created by jiachneyu on 2018/3/16.
 */
const route = require('koa-router2')
let router = new route();
let fs = require('fs');

let files = readDir(__dirname + '/controller');

map(files, '');

function map(files, r) {
    files.forEach(val => {
        const path = `./controller/${r}${val}`;
        const isFile1 = isFile(path);
        const isJs1 = isJs(path);
        if (isFile1 && isJs1) {
            let route = require(path);
            addMaping(route);
        }
        else if (!isFile1) {
            const dir = readDir(path);
            map(dir, `${val}/`)
        }
    })
}


function isJs(file) {
    return file.endsWith('.js')
}

function readDir(path) {
    return fs.readdirSync(path);
}

function isFile(path) {
    return fs.statSync(path).isFile()
}


function addMaping(route) {
    route.forEach(val => {
        if (val.method === "get") {
            router.get(val.path, val.handle)
        }
        else {
            router.post(val.path, val.handle)
        }
    })
}

function upload(router) {
    const multer = require('koa-multer');
    const md5 = require('md5');

    const storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, `./static/upload`)
        },
        filename: function (req, file, cb) {
            const fileFormat = (file.originalname).split(".")[1];
            console.log(file.originalname)
            const fileName = `${md5(Date.now())}.${fileFormat}`;
            cb(null, fileName)
        }
    })

    const upload = multer({storage: storage});
    router.post('/api/upload', upload.array("file"), async (ctx, next) => {
        const filePath = [];
        for (let x of ctx.req.files) {
            filePath.push(x.path.substring(6));
        }
        ctx.body = {
            code: 1,
            data: filePath
        }
    })
}

module.exports = function () {
    upload(router);
    return router.routes();
}
